//
//  CDraftList.m
//  HotDisPlus
//
//  Created by yilong zhang on 12-6-29.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "CDraftList.h"

@implementation CDraftList

@synthesize delegate;
@synthesize m_WaterFall;
@synthesize m_EditBtn;
@synthesize m_DelBtn;
@synthesize m_nSelDraft;

@synthesize m_Drafts;
@synthesize m_NativeCnt;

@synthesize m_bIsLoad;
@synthesize m_Task;
@synthesize m_NetCnt;

@synthesize m_Tags;

- (id)initWithFrame:(CGRect)frame Size:(CGSize)size
{
    self = [super initWithFrame:frame];
    if (self)
    {
        // Initialization code
        UIImageView *bg = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];
        bg.image = [UIImage imageNamed:@"appbg.jpg"];
        [self addSubview:bg];
        [bg release];
        
        UIImageView *topbar = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, frame.size.width, 51)];
        topbar.image = [UIImage imageNamed:@"barbg.png"];
        [self addSubview:topbar];
        [topbar release];
        
        topbar = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"draft.png"]];
        topbar.frame = CGRectMake((frame.size.width-40)/2, (51-17)/2, 40, 17);
        [self addSubview:topbar];
        [topbar release];
        
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        btn.frame = CGRectMake(10, 5, 60, 41);
        btn.tag = 0;
        [btn setBackgroundImage:[UIImage imageNamed:@"draftback.png"] forState:UIControlStateNormal];
        [btn addTarget:self action:@selector(OnButtonDown:) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:btn];
        
        m_EditBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        m_EditBtn.frame = CGRectMake(frame.size.width-70, 5, 60, 41);
        m_EditBtn.tag = 1;
        [m_EditBtn setBackgroundImage:[UIImage imageNamed:@"drafteditor.png"] forState:UIControlStateNormal];
        [m_EditBtn addTarget:self action:@selector(OnButtonDown:) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:m_EditBtn];
        
        m_DelBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        m_DelBtn.frame = CGRectMake(frame.size.width-70, 6, 60, 41);
        m_DelBtn.tag = 2;
        m_DelBtn.hidden = YES;
        [m_DelBtn setBackgroundImage:[UIImage imageNamed:@"draftdel.png"] forState:UIControlStateNormal];
        [m_DelBtn addTarget:self action:@selector(OnButtonDown:) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:m_DelBtn];
        
        m_Drafts = [[NSMutableArray array] retain];
        m_Tags = [[NSMutableArray array] retain];
        
        m_NativeCnt = [[CDesCounter alloc] init];
        m_NativeCnt.m_nLimit = 9;
        
        m_NetCnt = [[CDesCounter alloc] init];
        m_NetCnt.m_nLimit = 9;
        
        m_WaterFall = [[CWaterFall alloc] initWithFrame:CGRectMake(0, 45, frame.size.width, frame.size.height-45) ColNum:3 WaterDropSize:size];
        m_WaterFall.delegate = self;
        [self addSubview:m_WaterFall];
        [m_WaterFall release];
        
    }
    return self;
}

-(void)dealloc
{
    [self CancelTask];
    [m_Drafts release];
    [m_NativeCnt release];
    
    [super dealloc];
}

-(void)OnButtonDown:(UIButton *)sender
{
    //0-back
    if (0 == sender.tag)
    {
        [delegate DidDraftListClicked:0];
    }
    //1-edit
    else if (1 == sender.tag)
    {
        m_DelBtn.hidden = NO;
    }
    //2-del
    else if (2 == sender.tag)
    {
        [self DeleteDrafts];
    }
    else {;}
}

-(NSArray*)GetNativeDrafts
{
    if (m_NativeCnt.m_nLimit > 0)
    {
        NSArray *rets = [CDraft GetLimitDraft:@"Draft" Where:nil Offset:m_NativeCnt.m_nOffset Limit:m_NativeCnt.m_nLimit];
        if (rets)
        {
            [m_Drafts addObjectsFromArray:rets];
            [self AddDraftToList:rets];
            m_NativeCnt.m_nOffset += m_NativeCnt.m_nLimit;
            
            return rets;
        }
        else 
        {
            m_NativeCnt.m_nLimit = -1;
        }
    }
    
    return nil;
}

-(void)GetNetDarfts
{
    if (!m_bIsLoad)
    {
        m_bIsLoad = YES;

        NSMutableString *request = [NSMutableString string];
        [request appendFormat:@"mobikey=%@", [CUser DefaultUser].U_Token];
        [request appendFormat:@"&sessionid=%@", [CUser DefaultUser].U_Session];
        [request appendFormat:@"&action=%@", @"getTmp"];
        [request appendFormat:@"&cursor=%d", m_NetCnt.m_nOffset];
        [request appendFormat:@"&offset=%d", m_NetCnt.m_nLimit];
        
        NSLog(@"NetDrafts:%@", request);
        
        self.m_Task = [[CDownLoadManager DefaultDownLoadManager] AddTask:URL_GET_DRAFTS Sponsor:self PostData:[request dataUsingEncoding:NSUTF8StringEncoding] TimeOut:30 Data:[NSNumber numberWithInt:0] MType:Post UserInfo:nil];
    }
}

-(void)DidReveiveDrafts:(NSArray*)items
{
    NSMutableArray *rets = [NSMutableArray array];
    CDraft *draft = nil;
    for (NSDictionary *subdic in items)
    {
        draft = [[CDraft alloc] init];
        [draft SetDraftWithDic:subdic];
        if (0 == [draft SaveDraft:@"Draft"])
        {
            [rets addObject:draft];
            [draft CrreatePath];
        }
        [draft release];
    }
    
    if ([rets count] > 0)
    {
        [m_Drafts addObjectsFromArray:rets];
        [self AddDraftToList:rets];
        m_NetCnt.m_nOffset += [rets count];
    }
}

-(void)CancelTask
{
    [[CDownLoadManager DefaultDownLoadManager] CancelTask:m_Task];
    self.m_Task = nil;
}

-(void)AddDraftToList:(NSArray*)drafts
{
    UIImageView *btn = nil;
    CWaterDrop *drop = nil;
    NSData *data = nil;
    
    for (CDraft *draft in drafts)
    {
        drop = [m_WaterFall AddWaterDrop:nil];
        data = [draft GetMainImage];
        if (data)
        {
            drop.m_Image.image = [UIImage imageWithData:data];
        }
        else 
        {
            draft.m_Image = drop.m_Image;
            drop.m_Image.image = [UIImage imageNamed:@"icon.png"];
        }
        btn = [[UIImageView alloc] initWithFrame:CGRectMake(drop.frame.size.width-31, drop.frame.size.height-26, 30, 25)];
        drop.m_Obj = btn;
        [drop addSubview:btn];
        [btn release];
    }
}

-(void)AddNetDraftToList:(NSArray*)drafts
{
    //
}

-(void)OnDraftSelected:(UIImageView*)sender Tag:(CWaterDrop*)tag
{
    if (0 == sender.tag)
    {
        [m_Tags addObject:[m_Drafts objectAtIndex:tag.tag]];
        sender.tag = 1;
        sender.image = [UIImage imageNamed:@"sharecur.png"];
    }
    else 
    {
        [m_Tags removeObject:[m_Drafts objectAtIndex:tag.tag]];
        sender.tag = 0;
        sender.image = nil;
    }
}

-(void)DeleteDraft:(CDraft*)draft
{
    [CDraft RemoveDraft:@"Draft" Where:[NSString stringWithFormat:@"D_AID=%ld", [draft.m_lnID longValue]]];
    [[AppConfig DefaultAppConfig] RemovePathInApp:@"Documents/Draft" SubPath:[NSString stringWithFormat:@"%ld", [draft.m_lnID longValue]]];
    [m_Drafts removeObject:draft];
}

-(void)DeleteDrafts
{
    [[CRootCtrlManager DefaultRootCtrl] ShowLoadView:0.8 Title:@"删除中"];
    
    CDraft *draft = nil;
    //CWaterDrop *drop = nil;
    NSMutableArray *drafts = [NSMutableArray array];
    //for (for *drop in m_Tags)
    for (int i=0; i<[m_Tags count]; i++)
    {
        draft = [m_Tags objectAtIndex:i];
        //服务器草稿
        if (1 == [draft.m_nSate intValue])
        {
            [drafts addObject:draft];
        }
        [self DeleteDraft:draft];
    }
    
    [self DeleteNetDrafts:drafts];
    
    [m_Tags removeAllObjects];
    [m_WaterFall InitWaterFall];
    [self AddDraftToList:m_Drafts];
    
    if (0 == [drafts count])
        [[CRootCtrlManager DefaultRootCtrl] HiddenLoadView];
}

-(void)DeleteNetDrafts:(NSArray*)drafts
{
    if ([drafts count] > 0)
    {
        NSMutableString *tmpID = [NSMutableString string];
        int i = 0;
        for (CDraft *draft in drafts)
        {
            if (0 == i)
                [tmpID appendFormat:@"%ld", [draft.m_lnTID longValue]];
            else 
                [tmpID appendFormat:@",%ld", [draft.m_lnTID longValue]];
            
            i += 1;
        }
        NSMutableString *request = [NSMutableString string];
        
        [request appendFormat:@"action=%@", @"delTmp"];
        [request appendFormat:@"&mobikey=%@", [CUser DefaultUser].U_Token];
        [request appendFormat:@"&sessionid=%@", [CUser DefaultUser].U_Session];
        [request appendFormat:@"&tmpID=%@", tmpID];
        
        [[CDownLoadManager DefaultDownLoadManager] AddTask:URL_GETPRODUTS Sponsor:self PostData:[request dataUsingEncoding:NSUTF8StringEncoding] TimeOut:30 Data:[NSNumber numberWithInt:1] MType:Post UserInfo:nil];
    }
}

- (void)DidWaterFallButtom:(id)object
{
    if (![self GetNativeDrafts])
    {
        [self GetNetDarfts];
    }
}

- (void)WaterFallSelected:(id)object Index:(int)index
{
    if (!m_DelBtn.hidden)
    {
        CWaterDrop *drop = [m_WaterFall.m_Drops objectAtIndex:index];
        [self OnDraftSelected:drop.m_Obj Tag:drop];
    }
    else 
    {
        m_nSelDraft = index;
        CDraft *draft = [m_Drafts objectAtIndex:index];
        [[CUploadPageCtrl DefaultUploadPage].m_ImgPathes removeAllObjects];
        NSArray *ret = [[NSFileManager defaultManager] subpathsAtPath:draft.m_strPath];
        int nct = 0;
        for (NSString *str in ret)
        { 
            NSString *name = [str substringFromIndex:[str length]-3];
            if ([name isEqualToString:@"jpg"])
            {
                nct += 1;
                [[CUploadPageCtrl DefaultUploadPage].m_ImgPathes addObject:str];
            }
            [name release];
        }
        [CUploadPageCtrl DefaultUploadPage].m_UploadView.m_ImgCnt.text = [NSString stringWithFormat:@"%d", nct];
        [CUploadPageCtrl DefaultUploadPage].m_UploadView.m_bIsDraft = YES;
        [CUploadPageCtrl DefaultUploadPage].m_UploadView.m_Name.text = draft.m_strName;
        [CUploadPageCtrl DefaultUploadPage].m_UploadView.m_ResName.text = draft.m_strResName;
        [CUploadPageCtrl DefaultUploadPage].m_UploadView.m_Addr.text = draft.m_strAddr;
        [CUploadPageCtrl DefaultUploadPage].m_UploadView.m_Sum.text = draft.m_strSum;
        [CUploadPageCtrl DefaultUploadPage].m_UploadView.m_Image.image = [UIImage imageWithContentsOfFile:draft.m_strMainImgPath];
        
        [CUploadPageCtrl DefaultUploadPage].m_UploadView.m_AddrInfo.m_fX = [draft.m_nX floatValue];
        [CUploadPageCtrl DefaultUploadPage].m_UploadView.m_AddrInfo.m_fY = [draft.m_nY floatValue];
        [CUploadPageCtrl DefaultUploadPage].m_UploadView.m_AddrInfo.m_strCity = draft.m_strCity;
        [CUploadPageCtrl DefaultUploadPage].m_UploadView.m_AddrInfo.m_strProvince = draft.m_strProvince;
        [CUploadPageCtrl DefaultUploadPage].m_UploadView.m_AddrInfo.m_strCountry = draft.m_strCountry;
        [CUploadPageCtrl DefaultUploadPage].m_UploadView.m_AddrInfo.m_strSum = draft.m_strAddr;
        
        [[CUploadPageCtrl DefaultUploadPage] ShowUploadView:nil];
    }
}

-(void)DidOperationFinished:(COperation*)op Data:(NSData*)data Other:(id)other UserInfo:(id)userinfo
{
    NSString *json = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    NSDictionary *dic  = [json JSONValue];
    NSLog(@"%@", [dic objectForKey:@"Msg"]);
    
    int nCode = [other intValue];
    
    //get more drafts
    if (0 == nCode)
    {
        NSArray *items = [dic objectForKey:@"Resource"];
        if ([items isKindOfClass:[NSArray class]])
        {
            [self DidReveiveDrafts:items];
        }
        m_bIsLoad = NO;
        self.m_Task = nil;
    }
    else if (1 == nCode)
    {
        [[CRootCtrlManager DefaultRootCtrl] HiddenLoadView];
    }
    else {;}
    
    [json release];
}

-(void)DidOperationError:(COperation*)op Error:(NSError*)error Other:(id)other UserInfo:(id)userinfo
{
    int nCode = [other intValue];
    
    //get more drafts
    if (0 == nCode)
    {
        CDraft *draft = nil;
        if ([draft SaveDraft:@"Draft"])
        {
            //
        }
        else 
        {
            m_NetCnt.m_nOffset += 6;
        }
        m_bIsLoad = NO;
        self.m_Task = nil;
    }
    else if (1 == nCode)
    {
        [[CRootCtrlManager DefaultRootCtrl] HiddenLoadView];
    }
    else {;}
}

-(void)DidOperationTimeOut:(COperation*)op Other:(id)other UserInfo:(id)userinfo
{
    int nCode = [other intValue];
    
    //get more drafts
    if (0 == nCode)
    {
        m_bIsLoad = NO;
        self.m_Task = nil;
    }
    else if (1 == nCode)
    {
        [[CRootCtrlManager DefaultRootCtrl] HiddenLoadView];
    }
    else {;}
}

@end
